package com.mtk.launcher.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.cdl.library.config.DialogConfig;
import com.lark.wifi.util.MyLog;
import com.mtk.launcher.config.AppConfig;
import com.mtk.launcher.util.FileUtil;
import com.mtk.launcher.util.shared.SharedPerManager;

/***
 * 权限请求类
 * 作为程序入口
 * 权限使用方式，请查看源码位置
 * https://gitee.com/shotter_admin/permission-library
 */
public class PermissionActivity extends BaseActivity {

    private final int REQUEST_CODE_WRITE_SETTINGS = 100;
    private static final int REQUEST_CODE_PERMISSIONS = 101;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getScreenSize();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkAppWritSettingPermission();
    }

    private void checkAppWritSettingPermission() {
        if (hasWriteSettingsPermission()) {
            requestAppPermission();
            return;
        }
        Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        activityResultLauncher.launch(intent);
    }


    private String[] REQUIRED_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_NETWORK_STATE
    };

    private void requestAppPermission() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//            REQUIRED_PERMISSIONS = new String[]{
//                    Manifest.permission.READ_MEDIA_IMAGES,
//                    Manifest.permission.READ_MEDIA_VIDEO,
//                    Manifest.permission.READ_MEDIA_AUDIO,
//                    Manifest.permission.ACCESS_COARSE_LOCATION,
//                    Manifest.permission.ACCESS_FINE_LOCATION,
//                    Manifest.permission.CHANGE_NETWORK_STATE};
//        }

        if (!allPermissionsGranted()) {
            MyLog.permission("==requestPermissions=FALSE");
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            return;
        }
        MyLog.permission("==requestPermissions=TRUE");
        gotoMainView();
    }

    private void gotoMainView() {
        AppConfig.PERMISSION_COMPLAIY = true;
        FileUtil.creatPathNotExcit("程序初始化");
//        startActivity(new Intent(PermissionActivity.this, SleepActivity.class));
        startActivity(new Intent(PermissionActivity.this, MainActivity.class));
        finish();
    }


    private boolean allPermissionsGranted() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (allPermissionsGranted()) {
                gotoMainView();
            } else {
                showToastView("文件读写权限，申请失败，请检查");
                finish();
            }
        }
    }


    // 请求修改系统设置的权限
    ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    MyLog.permission("请求权限=onActivityResult=" + result.getResultCode());
                    if (result.getResultCode() != REQUEST_CODE_WRITE_SETTINGS) {
                        return;
                    }
                    if (hasWriteSettingsPermission()) {
                        requestAppPermission();
                    } else {
                        showToastView("没有系统读写权限，请检查");
                        finish();
                    }
                }
            });


    //==不用动得代码，主要关注上面得代码即可============================================================================

    // 检查是否有修改系统设置的权限
    private boolean hasWriteSettingsPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean isHasPermission = Settings.System.canWrite(this);
            MyLog.permission("是否有写入权限==" + isHasPermission);
            return isHasPermission;
        }
        MyLog.permission("是否有写入权限=低版本，有权限=");
        return true; // 6.0以下无需权限
    }

    public void getScreenSize() {
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(localDisplayMetrics);
        int width = localDisplayMetrics.widthPixels;
        int height = localDisplayMetrics.heightPixels;
        DialogConfig.screenWidth = width;
        DialogConfig.screenHeight = height;
        SharedPerManager.setScreenWidth(width);
        SharedPerManager.setScreenHeight(height);
    }

}
